<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function loginAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_Login();
 
        if( $request->isPost() )
        {
            if( $form->isValid($request->getPost()) )
            {
                $db = $this->_getParam('db');
                $adapter = new Zend_Auth_Adapter_DbTable(
                        $db,
                        'user',
                        'login',
                        'password'
                    );
                $adapter->setIdentity($form->getValue('login'));
                $adapter->setCredential(sha1($form->getValue('password')));
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($adapter);

                if( $result->isValid() )
                {
                   return $this->_helper->redirector('logged','user');
                }
                else
                {
                    if( $result->getCode() == Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND )
                    {
                        $form->getElement('login')->addError("Wrong login.");
                    }
                    else if( $result->getCode() == Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID )
                    {
                        $form->getElement('password')->addError("Wrong password.");
                    }
                    else
                    {
                        $form->getElement('login')->addError("Unable to identify you.");
                    }
                }
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        if( $auth->hasIdentity() )
        {
            $auth->clearIdentity();
        }
        return $this->_helper->redirector('index');
    }

    public function subscribeAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_Subscribe();
 
        if( $request->isPost() )
        {
            if( $form->isValid($request->getPost()) )
            {
                $userSubscribe = new Application_Model_User($form->getValues());
                $mapper = new Application_Model_UserMapper();
                $userSubscribe->setPassword(sha1($form->getValue('password')));
                $mapper->save($userSubscribe);
                
                // On envoie un mail de confirmation de la souscription.
                $mail = new Zend_Mail();
                $mail->setFrom('mlhuillier@ipsosenso.com','ZF test application');
                $mail->addTo($form->getValue('email'),$form->getValue('firstname').' '.$form->getValue('name'));
                $mail->setSubject('Subscription to ZF test application web site');
                $body = "<div><p>You have subscribed to the ZF test application web site.</p><p>Your login is : ".$form->getValue('login')."</p><p>Your password is : ".$form->getValue('password')."</p></div>";
                $mail->setBodyHtml($body);
                $mail->send();
                
                return $this->_helper->redirector('index');
            }
        }
        $this->view->form = $form;
    }

    public function unsubscribeAction()
    {
        $auth = Zend_Auth::getInstance();
        if( $auth->hasIdentity() )
        {
            $login = $auth->getIdentity();
            $mapper = new Application_Model_UserMapper();
            $user = $mapper->findOneByLogin($login);
            $mapper->remove($user->getId());
        }
        return $this->_helper->redirector('index');
    }

    public function loggedAction()
    {
        $auth = Zend_Auth::getInstance();
        if( $auth->hasIdentity() )
        {
            $login = $auth->getIdentity();
            $mapper = new Application_Model_UserMapper();
            $user = $mapper->findOneByLogin($login);
            $mapper = new Application_Model_UserCommentMapper();
            $this->view->comments = $mapper->findAllByUserId($user->getId());
            $this->view->user = $user;
        }
        else
        {
            return $this->_helper->redirector('index');
        }
    }

    public function editAction()
    {
        $request = $this->_request;
        if( $request->isXmlHttpRequest() ) // c'est une requete ajax comme prevu.
        {
            $auth = Zend_Auth::getInstance();
            if( $auth->hasIdentity() )
            {
                $login = $auth->getIdentity();
                $mapper = new Application_Model_UserMapper();
                $userEdit = $mapper->findOneByLogin($login);
                $form = new Application_Form_Edit();
                if( $request->isPost() )
                {
                    $values = $request->getPost();
                    $is_valid = false;
                    if( $form->isValid($request->getPost()) )
                    {
                        $is_valid = true;
                    }
                    $pwd1 = sha1($values['current_password']);
                    $pwd2 = $userEdit->getPassword();
                    if( $pwd1 != $pwd2 )
                    {
                        $form->getElement('current_password')->addError("Wrong password.");
                        $is_valid = false;
                    }
                    if( $is_valid )
                    {
                        $fields = array('name','firstname','email','login');
                        foreach($values as $key=>$value)
                        {
                            if( in_array($key,$fields) )
                            {
                                $userEdit->setAttribute($key,$value);
                            }
                        }
                        if( !empty($values['password']) )
                        {
                            $userEdit->setPassword(sha1($values['password']));
                            // On envoie un mail de confirmation si le mot de passe change.
                            $mail = new Zend_Mail();
                            $mail->setFrom('mlhuillier@ipsosenso.com','ZF test application');
                            $mail->addTo($userEdit->getEmail(),$userEdit->getFirstname().' '.$userEdit->getName());
                            $mail->setSubject('Edition of your pofil on ZF test application web site');
                            $body = "<div><p>You have edited your profil on the ZF test application web site.</p><p>Your login is : ".$userEdit->getLogin()."</p><p>Your password is : ".$values['password']."</p></div>";
                            $mail->setBodyHtml($body);
                            $mail->send();
                        }
                        $mapper->save($userEdit);
                        $this->view->success = 1;
                    }
                }
                else
                {
                    $form->setUserValues($userEdit);
                }
                $this->view->form = $form;
            }
            else
            {
                $this->view->errorLogged = 1;
            }
            $this->_helper->layout->disableLayout();
        }
        else
        {
            // On redirige vers la page d'accueil des utilisateurs.
            return $this->_helper->redirector('index');
        }
    }

    public function addcommentAction()
    {
        $request = $this->_request;
        if( $request->isXmlHttpRequest() ) // c'est une requete ajax comme prevu.
        {
            $auth = Zend_Auth::getInstance();
            if( $auth->hasIdentity() )
            {
                $form = new Application_Form_AddComment();

                if ($this->getRequest()->isPost())
                {
                    if ($form->isValid($request->getPost()))
                    {
                        $login = $auth->getIdentity();
                        $mapper = new Application_Model_UserMapper();
                        $user = $mapper->findOneByLogin($login);
                        $id = $user->getId();
                        $commentSubmit = new Application_Model_UserComment($form->getValues());
                        $mapper = new Application_Model_UserCommentMapper();
                        $commentSubmit->setUserId($id);
                        $mapper->save($commentSubmit);
                        $this->view->success = 1;
                    }
                }
                $this->view->form = $form;
            }
            else
            {
                $this->view->errorLogged = 1;
            }
            $this->_helper->layout->disableLayout();
        }
        else
        {
            // On redirige vers la page d'accueil des utilisateurs.
            return $this->_helper->redirector('index');
        }
        
    }

    public function deletecommentAction()
    {
        $auth = Zend_Auth::getInstance();
        if( $auth->hasIdentity() )
        {
            $login = $auth->getIdentity();
            $mapper = new Application_Model_UserMapper();
            $user = $mapper->findOneByLogin($login);
            $mapper = new Application_Model_UserCommentMapper();
            $mapper->remove($this->getRequest()->getParam('id'));
            return $this->_helper->redirector('logged');
        }
        else
        {
            return $this->_helper->redirector('index');
        }
    }


}

















